package com.heima.geteway.filter;

import com.heima.geteway.until.AppJwtUtil;
import com.sun.deploy.association.utility.AppUtility;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @author mgw
 * @create 2021/9/25 17:18
 */
@Component
public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory {

    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();
                //判断路径是否是登录是的话放行
                String path = request.getURI().getPath();
                if (path.contains("/login")){
                    return chain.filter(exchange);
                }
                //如果不是登录则获取token
                String token = request.getHeaders().getFirst("token");
                //判断是否游客是游客拦截
                String id1 = AppJwtUtil.getClaimsBody(token).get("id").toString();
                boolean b = AppJwtUtil.verifyToken(token);
                if (!AppJwtUtil.verifyToken(token)||"0".equals(AppJwtUtil.getClaimsBody(token).get("id").toString())){
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Flux.just(response.bufferFactory().wrap("请登录！".getBytes())));

                }
                return chain.filter(exchange);
            }
        };
    }
}
